package com.situ.mall.order.listener;

import com.situ.mall.common.constant.MqConstant;
import com.situ.mall.common.util.MultiDelayMessage;
import com.situ.mall.order.service.IOrderInfoService;
import com.situ.mall.pojo.entity.order.OrderInfo;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class OrderStatusListener {
    @Autowired
    private IOrderInfoService orderInfoService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(MqConstant.DELAY_ORDER_QUEUE),
            exchange = @Exchange(name = MqConstant.DELAY_EXCHANGE,delayed = "true"),
            key = {MqConstant.DELAY_ORDER_ROUTING_KEY}
    ))
    public void listenDelayMessage(MultiDelayMessage<Long> msg){
        System.out.println("OrderStatusListener.listenDelayMessage msg: " + msg);
        Long orderId = msg.getData();
        OrderInfo orderInfo = orderInfoService.getById(orderId);
        if(orderInfo == null || orderInfo.getOrderStatus()>1){
            return;
        }
        if (msg.hasNextDelay()){
            int delayValue = msg.removeNextDelay().intValue();
            rabbitTemplate.convertAndSend(MqConstant.DELAY_EXCHANGE, MqConstant.DELAY_ORDER_ROUTING_KEY, msg, new MessagePostProcessor() {
                @Override
                public Message postProcessMessage(Message message) throws AmqpException {
                    message.getMessageProperties().setDelay(delayValue);
                    return message;
                }
            });
            return;
        }
        //没有剩余延时时间,说明订单超时未支付
               orderInfoService.cancelOrder(orderId);
    }
}
